package core

import (
	_ "embed"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/mitchellh/go-homedir"
	"path/filepath"
	"strings"
)

var MockConfig SystemConfig

// SystemConfig 系统配置
type SystemConfig struct {
	Server Server    `toml:"server"`
	Docker Docker    `toml:"docker"`
	Email  Email     `toml:"email"`
	Jwt    JwtConfig `toml:"jwt"`
}

// Server 服务器相关配置
type Server struct {
	Port           int64    `toml:"port"`
	ContextPath    string   `toml:"context-path"`
	ReadTimeout    int      `toml:"read-timeout"`
	WriteTimeout   int      `toml:"write-timeout"`
	MaxHeaderBytes int      `toml:"max-header-bytes"`
	RunModel       string   `toml:"dev-model"`
	Storage        string   `toml:"storage"`
	WhiteList      []string `toml:"white-list"`
}

// Email 邮箱配置
type Email struct {
	Auth string `toml:"auth"` // 授权码
	Host string `toml:"host"` // 邮箱服务器
	Port int    `toml:"port"` // 端口
	Form string `toml:"form"` // 用户名
}

// Docker docker配置
type Docker struct {
	Address string `toml:"address"`
	Port    int    `toml:"port"`
}

// JwtConfig jwt配置
type JwtConfig struct {
	Issuer      string `toml:"issuer"`
	ExpiresTime int64  `toml:"expires-time"`
	SecretKey   string `toml:"secret-key"`
}

func (d *Docker) Link() string {
	return fmt.Sprintf("tcp://%s:%d", d.Address, d.Port)
}

func (s *Server) Whites() []string {
	result := make([]string, 0)
	for _, item := range s.WhiteList {
		if s.ContextPath == "" {
			result = append(result, item)
		} else {
			if strings.HasPrefix(s.ContextPath, "/") {
				result = append(result, s.ContextPath+item)
			} else {
				result = append(result, "/"+s.ContextPath+item)
			}
		}
	}
	return result
}

// Config 初始化配置文件
func Config() {
	path, _ := homedir.Expand("~/.helper/default.toml")
	if _, err := toml.DecodeFile(filepath.FromSlash(path), &MockConfig); err != nil {
		Log.Error("解析配置文件失败")
		panic("解析配置文件失败")
	}
	Log.Info("初始化配置文件成功")
}
